package com.bishe.psy.controller;

import com.bishe.psy.common.AppResult;
import com.bishe.psy.common.ResultCode;
import com.bishe.psy.config.AppConfig;
import com.bishe.psy.exception.ApplicationException;
import com.bishe.psy.model.*;
import com.bishe.psy.service.IArticleService;
import com.bishe.psy.service.ILikeArticleService;
import com.bishe.psy.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: L
 * Date: 2024-04-10
 * Time: 17:07
 */

@Slf4j
@Api(tags = "文章接口")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService iArticleService;



    //发布帖子
    @ApiOperation("发布文章方法")
    @PostMapping("/distribute")
    public AppResult distribute(HttpServletRequest request,
                                @ApiParam(value = "标题") @RequestParam("title") String title,
                                @ApiParam(value = "正文")  @RequestParam("content") String content) {

        //1.从session中获取用户信息
        HttpSession session = request.getSession(false);
        ConUser conUser = (ConUser) session.getAttribute(AppConfig.USER_SESSION);

        //2.构建文章
        Article article = new Article();
        article.setUserId(conUser.getId());
        article.setTitle(title);
        article.setContent(content);


        //3.对前端传入的参数进行校验
        if(StringUtil.isEmpty(title) || StringUtil.isEmpty(content)) {
            log.warn("请输入内容");
            return AppResult.failed("请输入内容");
        }

        //4.参数校验通过传入服务端
        iArticleService.create(article);

        //5.插入成功返回json数据给前端

        return AppResult.success();
    }

    @ApiOperation("获取帖子列表接口")
    @GetMapping("/articlelist")
    public AppResult<List<Article>> getAllArticleList() {

        //1.获取文章表中全部的文章
        List<Article> articles = iArticleService.selectAll();

        //2.检查articles返回是否为null
        if(articles == null) {
            //若当前articles为null，将articles转换变成空集合[]
            articles = new ArrayList<>();
        }

        //3.返回数据
        return AppResult.success(articles);

    }

    @ApiOperation("查询在线咨询师接口")
    @GetMapping("/isReign")
    public AppResult<List<Article>> selectConByIsReign() {

        List<Article> articles = iArticleService.selectConByIsReign();
        if(articles == null) {
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);

    }

    @ApiOperation("获取帖子id接口")
    @GetMapping("/detail")
    public AppResult<Article> selectArticleById(HttpServletRequest request,
            @ApiParam(value = "帖子id") @RequestParam("id") Long id,Integer currentIdentity) {

        System.out.println("查看帖子的id");
        System.out.println(id);

        System.out.println("身份 = " + currentIdentity );

        //1.参数检验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }

        //2.调用service
        Article article = iArticleService.selectArticleById(id);


        //3.参数校验
        if(article == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //4.获取当前登录用户的身份信息
        HttpSession session = request.getSession(false);

        //若 currentIdentity == 1 或者 currentIdentity == 3，说明是学生身份和管理员身份，直接说明不是文章作者
        //currentIdentity == 2 说明当前登录用户为咨询师，则需要判断当前文章发布的作者是否位当前登录的咨询师
        //在article文章类中添加属性isOwn，若isOwn为true则是作者
        if(currentIdentity == 1 || currentIdentity == 3 ) {
            article.setOwn(false);
        } else {
            ConUser conUser  = (ConUser) session.getAttribute(AppConfig.USER_SESSION);
            System.out.println("登录咨询师id = " + conUser.getId());
            System.out.println("文章作者id = " + article.getUserId());
            if(conUser.getId() == article.getUserId()) {
                article.setOwn(true);
            }
        }
        //5.返回参数结果
        return AppResult.success(article);
    }


    @ApiOperation("获取咨询师id接口")
    @GetMapping("/selectById")
    public AppResult<Article> selectConById(@ApiParam(value = "咨询师id") @RequestParam("id") Long id) {


        //1.参数校验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //2.调用service
        Article article = iArticleService.selectConById(id);

        //3.参数校验
        if(article == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //4.返回参数
        return AppResult.success(article);
    }

    @ApiOperation("修改帖子内容接口")
    @GetMapping("/modify")
    public AppResult modifyArticle(HttpServletRequest request,
                                   @ApiParam(value = "文章id") @RequestParam("id") Long id,
                                   @ApiParam(value = "文章标题") @RequestParam("title")String title,
                                   @ApiParam(value = "文章内容") @RequestParam("content")String content,
                                   Long currentIdentity ) {

        //1.参数非空校验
        if(id == null || id <= 0 || currentIdentity == null || currentIdentity <= 0
        || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }


        //2.获取登录用户的信息,只有咨询师并且为作者才能修改文章
        HttpSession session = request.getSession(false);
       if(currentIdentity == 1 || currentIdentity == 3) {
           log.warn(ResultCode.FAILED_FORBIDDEN.toString());
           return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
       }
       ConUser conUser = (ConUser) session.getAttribute(AppConfig.USER_SESSION);

       //3.根据文章id查询得到该文章的作者的id
        Article article = iArticleService.selectByPrimaryKey(id);
        if(article == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //4.判断当前登录用户是否为当前文章作者
       if(conUser.getId() != article.getUserId() ) {
           log.warn(ResultCode.FAILED_FORBIDDEN.toString());
           return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
       }

       //5.判断当前帖子状态, == 1说明已经被删除
        if(article.getDeleteState() == 1) {
            log.warn("文章已被删除");
            return AppResult.failed("文章已被删除");
        }

        //6.调用service
        iArticleService.modifyArticle(id,title,content);
        log.info("帖子更新成功");

        //7.返回结果
        return AppResult.success();
    }




    @ApiOperation("删除帖子接口")
    @GetMapping("/delete")
    public AppResult deleteArticleById(HttpServletRequest request,
                                       @ApiParam("文章id") @RequestParam("id") Long id,
                                       @ApiParam("用户身份") Long currentIdentity) {

        System.out.println("删除帖子查看传递的id");
        System.out.println(id);

        //1.参数校验
        if(id == null || id <= 0 || currentIdentity == null || currentIdentity <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //2.判断当前登录的用户是否为咨询师，是咨询师才有删除文章的功能
        if(currentIdentity != 2) {
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        //3.获取咨询师的信息
        HttpSession session = request.getSession(false);
        ConUser conUser = (ConUser) session.getAttribute(AppConfig.USER_SESSION);

        //4.根据文章id获取文章信息
        Article article = iArticleService.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        //5.判断登录的用户是否为该篇文章的作者
        if(article.getUserId() != conUser.getId()) {
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        //6.调用service
        iArticleService.deleteById(id);

        //7.返回结果
        return AppResult.success();
    }


    @ApiOperation("根据用户id获取文章信息接口")
    @GetMapping("/getArticleByUserId")
    public AppResult<List<Article>> getArticleByUserId(HttpServletRequest request,
                                                       @ApiParam(value = "用户id") @RequestParam(value = "userId",required = false) Long userId) {

        //1.当传递的userId为空时,直接从session中获取用户信息
        if(userId == null) {
            HttpSession session = request.getSession(false);
            ConUser conUser = (ConUser) session.getAttribute(AppConfig.USER_SESSION);
            userId = conUser.getId();
        }

        //2.当传递用户userId时直接调取service,不传递时，将userId赋值后也调用
        List<Article> articles = iArticleService.selectByUserId(userId);

        return AppResult.success(articles);

    }
}
